package com.example.widgetcase.slice;

import com.example.widget_lib.utils.Util;
import com.example.widgetcase.ResourceTable;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;

public class CustomScrollViewAbility extends BaseSlice {

    private static final int MOCK_ITEM_COUNT = 20;
    // 屏幕宽高
    private int mScreenW, mScreenH;
    // 控件宽高
    private int mWidth, mHeight;

    @Override
    public int getChildUIContent() {
        return ResourceTable.Layout_touch_custom_scrollview;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);

        DirectionalLayout container = (DirectionalLayout) findComponentById(ResourceTable.Id_item_container);

        int screen[] = Util.getScreenWH(getContext());
        mScreenW = screen[0];
        mScreenH = screen[1];

        getUITaskDispatcher().asyncDispatch(() -> {

            int matchParent = ComponentContainer.LayoutConfig.MATCH_PARENT;
            int matchContent = ComponentContainer.LayoutConfig.MATCH_CONTENT;
            DirectionalLayout.LayoutConfig config = new DirectionalLayout.LayoutConfig(matchParent, matchContent);
            container.setLayoutConfig(config);

            int top = 0;
            for (int i = 0; i < MOCK_ITEM_COUNT; i++) {
                int width = mScreenW;
                int height = mScreenH / 2;
                int left = 0;
                int right = left + width;
                int bottom = top + height;

                // 计算控件实际宽高
                if (bottom > mHeight) {
                    mHeight = bottom;
                }
                if (right > mWidth) {
                    mWidth = right;
                }

                // 生成测试内容
                Text tv = new Text(getContext());
                RgbColor color;
                if (i % 2 == 0) {
                    color = RgbColor.fromArgbInt(Color.BLUE.getValue());
                } else {
                    color = RgbColor.fromArgbInt(Color.GREEN.getValue());
                }
                ShapeElement element = new ShapeElement();
                element.setRgbColor(color);
                tv.setBackground(element);

                tv.setTextColor(Color.WHITE);
                tv.setText("item:" + i);
                container.addComponent(tv);

                tv.setLayoutConfig(new DirectionalLayout.LayoutConfig(right - left, bottom - top));

                tv.setLeft(left);
                tv.setTop(top);
                tv.setRight(right);
                tv.setBottom(bottom);
                top += height;
                // 留20px的行间距
                top += MOCK_ITEM_COUNT;
            }
        });

    }
}
